package com.example.demo.service;

import com.example.demo.common.Func;
import com.example.demo.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;

@Service
public class UploadService {

    public void uploadChunkFile(MultipartFile chunk, int currentChunk, String fileName) {
        String filePath = Func.getRootPath() + "/file/chunk/" + fileName;
        File chunkPath = new File(filePath);
        if (!chunkPath.exists()) {
            chunkPath.mkdirs();
        }

        String chunkTempPath = "chunk_" + currentChunk;
        File chunkFile = new File(chunkPath, chunkTempPath);

        OutputStream os = null;
        byte[] chunkByte = null;
        try {
            os = new FileOutputStream(chunkFile);
            chunkByte = chunk.getBytes();
            os.write(chunkByte);
            os.flush();
        }
        catch (Exception ex) {
            throw new BusinessException("上传分片异常:" + ex);
        }
        finally {
            if (chunkByte != null) {
                chunkByte.clone();
            }
            if (os != null) {
                try {
                    os.close();
                }
                catch (Exception ignored) {}
            }
        }
    }

    public void mergeChunksFile(String fileName) {
        String filePath = Func.getRootPath() + "/file/chunk/" + fileName;
        File chunkPath = new File(filePath);

        String resultPath = Func.getRootPath() + "/file/chunk/result/" + fileName;
        File mergedFile = new File(resultPath);

        OutputStream os = null;
        try {
            os = new FileOutputStream(mergedFile);
            int len = chunkPath.listFiles().length;
            for (int i = 0; i < len; i++) {
                File chunkFile = new File(chunkPath, "chunk_" + i);
                Files.copy(chunkFile.toPath(), os);
                chunkFile.delete();
            }
        }
        catch (Exception ex) {
            throw new BusinessException("合并分片异常:" + ex);
        }
        finally {
            if (os != null) {
                try {
                    os.close();
                }
                catch (Exception ignored) {}
            }
            if (chunkPath != null) {
                chunkPath.delete();
            }
        }
    }

}
